<template>
  <div class="container">
    <el-form ref="dataFormMeter" :rules="rules" :model="conModel" label-width="82px" size="mini" class="search_content">
      <el-row :gutter="24">
        <el-col :span="4" class="common_input">
          <el-form-item label="铭牌号:" prop="BarCode">
            <el-input v-model="conModel.BarCode" clearable placeholder="请输入铭牌号" @keyup.enter.native="getList('search')" />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_input">
          <el-form-item label="数据类型:">
            <el-select v-model="conModel.Type" clearable placeholder="请选择数据类型">
                <el-option key="1" label="标况流量" value="1" />
                <el-option key="2" label="工况流量" value="2" />
                <el-option key="3" label="温度" value="3" />
                <el-option key="4" label="压力" value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_picker">
          <el-form-item label="开始时间:" prop="ReportDate">
            <el-date-picker
              v-model="conModel.StartTime"
              type="datetime"
                format="yyyy-MM-dd HH:mm"
                alue-format="yyyy-MM-dd HH:mm"
              placeholder="请选择时间"
              size="mini"
              class="search_common_picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_picker">
          <el-form-item label="结束时间:" prop="ReportDate">
            <el-date-picker
              v-model="conModel.EndTime"
              type="datetime"
                format="yyyy-MM-dd HH:mm"
                alue-format="yyyy-MM-dd HH:mm"
              placeholder="请选择时间"
              size="mini"
              class="search_common_picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="sel_meter">
          <el-button size="mini" @click="meterPopup()">
            选择铭牌号
          </el-button>
        </el-col>
        <el-col :span="1" class="common_query">
          <el-button size="mini" @click="getList('search')">
            查询
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="table_content">
        <div id="main" v-loading="listLoading" />
    </div>
    <!-- 通信编号 -->
    <el-dialog title="表计信息" :visible.sync="dialogFormMeter" class="newel-dialog sel_meter_popup">
      <div class="el-dialog__body">
        <el-form :model="conModelMeter" label-width="72px" size="mini" class="search_content">
          <el-col :span="4" class="common_input">
            <el-form-item label="铭牌号:">
              <el-input v-model="conModelMeter.BarCode" clearable placeholder="请输入铭牌号" @keyup.enter.native="GetMeterInfo('search')" />
            </el-form-item>
          </el-col>
          <el-col :span="4" class="common_input">
            <el-form-item label="客户名称:">
              <el-input v-model="conModelMeter.Name" clearable placeholder="请输入客户名称" @keyup.enter.native="GetMeterInfo('search')" />
            </el-form-item>
          </el-col>
          <el-col :span="1" class="common_query">
            <el-button size="mini" @click="GetMeterInfo('search')">
              查询
            </el-button>
          </el-col>
        </el-form>
        <!-- 翻页多选 -->
        <!-- :row-key="(row)=>{ return row.MeterId}"
        :reserve-selection="true" -->
        <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="listMeter"
            fit
            style="width: 100%;"
            :stripe="true"
            @select="mySelect_2"
            @select-all="mySelect_2"
            :row-key="(row)=>{ return row.MeterId}"
            
            >
            <el-table-column
                :reserve-selection="true"
                type="selection"
            />
          <el-table-column align="center" label="IC卡卡号">
            <template slot-scope="scope">
              {{ scope.row.CardNo }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="铭牌号">
            <template slot-scope="scope">
              {{ scope.row.BarCode }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="客户名称">
            <template slot-scope="scope">
              {{ scope.row.CustomerName }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="计量点">
            <template slot-scope="scope">
              {{ scope.row.Address }}
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="totalMeter>0" :total="totalMeter" :PageIndex.sync="Meter.PageIndex" :PageSize.sync="Meter.PageSize" @pagination="GetMeterInfo" />
        <div slot="footer" class="dialog-footer">
          <el-button class="add_edit_btn determine analysis_btn" @click="determine()">
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { SomeMeterUseStatics, GetMeterInfo } from '@/api/basics'
import moment from 'moment'
import echarts from 'echarts'

export default {
  name: 'Analysis',
  components: {
    Pagination
  },
  data() {
    return {
        Parameter: {
          PageSize: 100,
          PageIndex: 1,
          OrderBy: 'acquisition_time',
          isDesc: 'false'
        },
        conModel: {
          StartTime: moment(new Date()).format('YYYY-MM-01 HH:mm'),
          EndTime: moment(new Date()).format('YYYY-MM-DD HH:mm'), // YYYY-MM-DD
          BarCode: '',
          Type: '1'
        },
        conModelCopy: {},
        listLoading: false,
        list: [],
        myChart: null,
        titleBarCode: [],
        xArr: [],
        yArr: [],
        screenWidth: document.body.clientWidth,
        Meter: {
          PageSize: 10,
          PageIndex: 1,
          OrderBy: 'MeterId',
          isDesc: true
        },
        conModelMeter: {
          BarCode: '',
          Name: ''
        },
        conModelMeterCopy: {},
        listMeter: [],
        totalMeter: 0,
        dialogFormMeter: false,
        batchRow: [],
        PageIndex: 1,
        useStatics:[], //使用量
        useStaticsResult: false,
        rules: {

        }
      }
    },
    computed: {
      sidebar() {
        const _this = this
        return _this.$store.getters.sidebar.opened
      }
    },
    mounted () {
      const that = this
      window.onresize = () => {
        return (() => {
          window.screenWidth = document.body.clientWidth
          that.screenWidth = window.screenWidth
        })()
      }
      that.$nextTick(function() {
        that.drawLine('main')
      })  
    },
    watch: {
      sidebar(opened) {
        const _this = this;
        _this.main = echarts.init(document.getElementById('main'))
        setTimeout(function(){
          _this.main.resize()
          
        },400)
      },
      screenWidth(val){
        this.screenWidth = val
        const _this = this;
        _this.main = echarts.init(document.getElementById('main'))
        setTimeout(function(){
          _this.main.resize()
        },400)
      }
    },
  created() {
    // this.getList()
  },
  methods: {
    drawLine() {
        this.myChart = echarts.init(document.getElementById('main'));
        this.myChart.clear()
        let titleLegend = []
        if (this.titleBarCode.length > 0) {
          titleLegend = Array.from(new Set(this.titleBarCode))
        }
        var option = {
        title: {
          text: '分析图'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: titleLegend
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            aveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xArr,
        },
        yAxis: {
          type: 'value',
        },
        series: this.yArr
        };
        option && this.myChart.setOption(option);
        window.addEventListener("resize", () => {
          if(this.myChart){
            this.myChart.resize()
          }
        })
    },
    getList(init) {
      if (init === 'search') {
        this.conModelCopy = {}
        this.PageIndex = 1
        this.xArr = []
        this.yArr = []
        this.titleBarCode = []
        this.useStatics = []
      }
      if (this.conModel.StartTime !== null && init === 'search') {
        this.conModelCopy.StartTime = moment(this.conModel.StartTime).format('YYYY-MM-DD HH:mm')
      }
      if (this.conModel.EndTime !== null && init === 'search') {
        this.conModelCopy.EndTime = moment(this.conModel.EndTime).format('YYYY-MM-DD HH:mm')
      }
      if (this.conModel.BarCode.trim() !== '' && init === 'search') {
        this.conModelCopy.BarCodes = this.conModel.BarCode.trim()
      }
      if (this.conModel.Type !== '' && init === 'search') {
        this.conModelCopy.Type = this.conModel.Type
      }
      var Parameter = {
        ...this.Parameter,
        PageIndex: this.PageIndex,
        ...this.conModelCopy
      }
      this.listLoading = true
      // 0000000424,0000000423
      SomeMeterUseStatics(Parameter).then(res => {
        this.list = res.Data
        this.useStatics.push(this.list)
        this.PageIndex++
        let len = this.list.length
        if (len !== 0) {
          return this.getList()
        } else {
          setTimeout(() => {
            this.PageIndex = 1
            // 所有的数据扁平化
            const changeList = []
            this.useStatics.map(it => {
              changeList.push(...it)
            })
            const dataSource = changeList.reduce((pre, next, idx) => {
            const filterItem = pre.filter((it ,idx)=> it.BarCode == next.BarCode);
            if (filterItem && filterItem[0]) {
                pre.map((it,index) => {
                  if(it.BarCode == filterItem[0].BarCode) {
                    pre[index].data.push(next.Value)
                  }
                })
                } else {
                  pre.push({
                    ...next,
                    name: next.BarCode,
                    type: 'line',
                    data: [next.Value]
                  })   
                }
                return pre
            },[])
            this.yArr = dataSource
            changeList.map(item => {
              this.titleBarCode.push(item.BarCode)
              this.xArr.push(moment(item.acquisition_time).format('YYYY-MM-DD HH:mm:ss'))
            })
            this.xArr = Array.from(new Set(this.xArr))
            this.$nextTick(function() {
              this.drawLine('main')
            })  
          },0)
        }
        this.listLoading = false
        return
        if (this.list.length > 0) {
          const dataSource = this.list.reduce((pre, next, idx) => {
            const filterItem = pre.filter((it ,idx)=> it.BarCode == next.BarCode);
            if (filterItem && filterItem[0]) {
              pre.map((it,index) => {
                if(it.BarCode == filterItem[0].BarCode) {
                  pre[index].data.push(next.Value)
                }
              })
              } else {
                pre.push({
                  ...next,
                  name: next.BarCode,
                  type: 'line',
                  data: [next.Value]
                })   
              }
              return pre
            },[])
            this.yArr = dataSource
            this.list.map(item => {
              this.titleBarCode.push(item.BarCode)
              this.xArr.push(moment(item.acquisition_time).format('YYYY-MM-DD HH:mm:ss'))
            })
            this.xArr = Array.from(new Set(this.xArr))
            this.$nextTick(function() {
              this.drawLine('main')
            })  
        } else {
          this.$message({
            message: '暂无数据',
            type: 'info'
          })
          this.listLoading = false
          return
        }
        this.listLoading = false
      })
    },
    // 表计信息弹窗
    meterPopup() {
      this.conModelMeter = {
        BarCode: '',
        Name: ''
      }
      this.Meter.PageIndex = 1
      this.conModelMeterCopy = {}
      this.listMeterType = []
      this.dialogFormMeter = true
      this.GetMeterInfo()
      this.$nextTick(() => {
        //  清空多选框
        this.batchRow = []
        this.$refs.multipleTable.clearSelection();
      })
    },
    GetMeterInfo(init) {
      if (init === 'search') {
        this.Meter.PageIndex = 1
        this.conModelMeterCopy = {}
      }
      if (this.conModelMeter.BarCode.trim() !== '' && init === 'search') {
        this.conModelMeterCopy.BarCode = this.conModelMeter.BarCode.trim()
      }
      if (this.conModelMeter.Name.trim() !== '' && init === 'search') {
        this.conModelMeterCopy.Name = this.conModelMeter.Name.trim()
      }
      this.listLoading = true
      let Parameter = {
        ...this.Meter,
        ...this.conModelMeterCopy
      }
      GetMeterInfo(Parameter).then(res => {
        this.listMeter = res.Data
        this.totalMeter = res.Total
        this.listLoading = false
      })
    },
    // 选择
    mySelect_2(selection, row) {
      const arr = []
      selection.map(it => {
        arr.push(it.BarCode)
      })
      this.batchRow = arr
    },
    // 确定
    determine() {
      this.dialogFormMeter = false
      this.conModel.BarCode = this.batchRow.join(',')
    }
  }
}
</script>

<style>
#main {
  margin-top: 40px;
  width: 100%;
  height: 500px;
}

.analysis_btn {
  float: right;
}
</style>
